import 'package:bigegg/data/repository/xmm_remote_repository.dart';
import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../../common/get/controller/xmm_base_controller.dart';
import '../../../entity/articel/xmm_article_info.dart';

class XmmArticleDetailController extends XmmBaseGetxController {
  var remoteRepository = XmmRemoteRepository();

  final articleInfo = (Get.arguments as XmmArticleInfo).obs;

  final articleDescription = ''.obs;

  bool isMine = (Get.arguments as XmmArticleInfo).wallUser?.userId ==
      XmmAccountManager.instance.user.userId;

  @override
  void onInit() {
    super.onInit();
    articleDescription.value = articleInfo.value.description ?? "";
  }

  void sendComment(String text) {
    var comment = XmmArticleComment(
      content: text,
      nickname: XmmAccountManager.instance.user.nickname ?? "",
      avatar: XmmAccountManager.instance.user.avatarUrl ?? "",
    );
    if (articleInfo.value.commentList?.isEmpty ?? true) {
      articleInfo.value.commentList = <XmmArticleComment>[comment];
    } else {
      articleInfo.value.commentList?.add(comment);
    }
    articleInfo.refresh();
    XmmAccountManager.instance.updateArticle();
  }

  Future<void> follow(String userId) async {
    try {
      EasyLoading.show();
      await XmmAccountManager.instance.follow(userId);
      articleInfo.refresh();
      XmmToastUtils.show("Follow Successfully");
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> unfollow(String userId) async {
    try {
      EasyLoading.show();
      await XmmAccountManager.instance.unfollow(userId);
      articleInfo.refresh();
      XmmToastUtils.show("Unfollow Successfully");
    } finally {
      EasyLoading.dismiss();
    }
  }

  void like() {
    EasyLoading.show();
    articleInfo.value.isLikeByMe = true;
    articleInfo.value.followed = (articleInfo.value.followed ?? 1) + 1;
    articleInfo.refresh();
    XmmAccountManager.instance.updateArticle();
    EasyLoading.dismiss();
  }

  void unLike() {
    EasyLoading.show();
    articleInfo.value.isLikeByMe = false;
    articleInfo.value.followed = (articleInfo.value.followed ?? 1) - 1;
    articleInfo.refresh();
    XmmAccountManager.instance.updateArticle();
    EasyLoading.dismiss();
  }

  void translate(String text) async {
    String? txt = await remoteRepository.translate(text);
    articleDescription.value = txt;
  }
}
